package heap;

import java.util.Arrays;

/**
 * Creared with IntelliJ IDEA.
 * Description:创建自己的堆
 * User:yxd
 * Date:2022-01-22
 * Time:10:42
 */
public class TestHeap {
    public int[] elem;
    public int usedSize;

    public TestHeap() {
        this.elem = new int[10];
    }

    /**
     * 向下调整函数的实现
     * @param parent 每棵树的根节点
     * @param len 每棵树的调整的结束位置  10
     */
    public void shiftDown(int parent,int len) {
        int child = 2*parent+1;
//1、最起码 是有左孩子的，至少有1个孩子
        while (child < len) {
            if(child+1 < len && elem[child] < elem[child+1]) {
                child++;//保证当前左右孩子最大值的下标
            }
            if(elem[parent] < elem[child]){
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                parent = child;
                child = 2*parent+1;
            }else{
                break;
            }
        }
    }
//创建一个大根堆
    public void createHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
        for (int parent = (usedSize-1-1)/2; parent >= 0 ; parent--) {
//调整
            shiftDown(parent,usedSize);
        }
    }
    private void shiftUp(int child) {
        int parent = (child - 1) / 2;
        while(child > 0){
            if(elem[parent] > elem[child]){
                break;
            }else{
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            }
        }

    }
//放元素
    public void offer(int val) {
        if(isFull()) {
            //扩容
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize++] = val;
        //注意这里传入的是usedSize-1
        shiftUp(usedSize-1);
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }
    //出队
    public int poll(){
        if(isEmpty()){
            throw  new RuntimeException("优先级队列为空！");
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize - 1];
        elem[usedSize - 1] = tmp;
        usedSize -- ;
        shiftDown(0,usedSize);
        return tmp;
    }
    //优先级队列对顶
    public int peek(){
        if(isEmpty()){
            throw  new RuntimeException("优先级队列为空！");
        }
        return elem[0];
    }
    public boolean isEmpty() {
        return usedSize == 0;
    }
    //堆排序
    public void heapSort() {
        int end = this.usedSize - 1;
        while(end != 0){
            int tmp = elem[0];
            elem[0] = elem[end];
            elem[end] = tmp;
            shiftDown(0,end);
            end --;
        }
    }
}
